﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace TanmiaGrp.Basis.Core
{
    [Flags]
    public enum AssociationTypeEnum
    {
        Composition = 1,
        Aggregation = 2,
        Association = 4
    }

    public class AssociationTypeAttribute : Attribute
    {
        public AssociationTypeEnum AssociationType { get; private set; }

        public AssociationTypeAttribute(AssociationTypeEnum associationType)
        {
            this.AssociationType = associationType;
        }

        public static IEnumerable<BusinessObject> GetAssociationObjects(BusinessObject bizObj)
        {
            foreach (PropertyInfo prop in GetAssociations(bizObj, AssociationTypeEnum.Association))
                yield return prop.GetValue(bizObj) as BusinessObject;
        }

        public static IEnumerable<IEnumerable<BusinessObject>> GetAssociationCollections(BusinessObject bizObj, AssociationTypeEnum associationType)
        {
            foreach (PropertyInfo prop in GetAssociations(bizObj, associationType))
            {
                object value = prop.GetValue(bizObj);
                if (value != null)
                    yield return (value as IEnumerable).Cast<BusinessObject>();
            }
        }

        private static PropertyInfo[] GetAssociations(BusinessObject bizObj, AssociationTypeEnum associationType)
        {
            return bizObj.GetType()
                .GetProperties()
                .Where(p => p.IsDefined(typeof(AssociationTypeAttribute), false))
                .Where(p => p.GetCustomAttribute<AssociationTypeAttribute>().AssociationType == associationType)
                .ToArray();
        }
    }
}
